package com.yy.jhl.ui.manager.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.foamtrace.photopicker.ImageCaptureManager;
import com.foamtrace.photopicker.ImageConfig;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.yy.common.base.BaseActivity;
import com.yy.common.commonutils.Base64;
import com.yy.common.commonutils.FileUtil;
import com.yy.common.commonutils.ImageLoaderUtils;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonutils.TimeUtil;
import com.yy.common.commonwidget.LoadingDialog;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;
import com.yy.jhl.app.AppConstant;
import com.yy.jhl.bean.FileInfo;
import com.yy.jhl.bean.LogisticsInfo;
import com.yy.jhl.bean.ProductInfo;
import com.yy.jhl.interfaces.CommonCallBack;
import com.yy.jhl.interfaces.FileUploadCallBack;
import com.yy.jhl.interfaces.PictureCallBack;
import com.yy.jhl.interfaces.UploadCallBack;
import com.yy.jhl.ui.main.activity.ClipImageActivity;
import com.yy.jhl.ui.manager.adapter.PictureAdapter;
import com.yy.jhl.ui.manager.adapter.ProductAdapter;
import com.yy.jhl.ui.manager.contract.OutboundSubmitContract;
import com.yy.jhl.ui.manager.presenter.OutboundSubmitPresenter;
import com.yy.jhl.util.DataRequestUtil;
import com.yy.jhl.util.DialogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yy.jhl.ui.main.activity.TakePhotoUploadActivity.UPLOAD_IMG;

/**
 * 出库准备 数据提交
 * Created by libingn on 2017/12/7.
 */

public class OutboundSubmitActivity extends BaseActivity<OutboundSubmitPresenter> implements OutboundSubmitContract.View {
    @BindView(R.id.add_pic_img)
    ImageView addPicImg;
    @BindView(R.id.chuku_product_parent)
    LinearLayout chukuProductParent;
    @BindView(R.id.note_edit)
    EditText noteEdit;
    @BindView(R.id.time_text)
    TextView timeText;
    @BindView(R.id.add_text)
    TextView addText;
    @BindView(R.id.time_parent)
    LinearLayout timeParent;
    @BindView(R.id.product_list_parent)
    LinearLayout productListParent;
    @BindView(R.id.ensure_btn)
    Button ensureBtn;
    String orderId = "";
    @BindView(R.id.listview)
    ListView listview;
    ProductAdapter productAdapter;
    boolean isSubmitData = false;
    List<ProductInfo> productList = null;
    String attachPath = "";//附件
    ArrayList<String> attachPaths = new ArrayList<>();
    String batchId = "";
    LogisticsInfo logisticsInfo;
    @BindView(R.id.noScrollgridview)
    GridView noScrollgridview;
    PictureAdapter pictureAdapter;
    ImageCaptureManager captureManager;
    private String productItems = "";
    private String productToTalPrice = "";
    public static void startAction(Context mContext, String orderId, int requestCode) {
        Intent intent = new Intent(mContext, OutboundSubmitActivity.class);
        intent.putExtra("orderId", orderId);
        ((Activity) mContext).startActivityForResult(intent, requestCode);
    }

    public static void startAction(Context mContext, String orderId, LogisticsInfo logisticsInfo) {
        Intent intent = new Intent(mContext, OutboundSubmitActivity.class);
        intent.putExtra("orderId", orderId);
        intent.putExtra("logisticsInfo", logisticsInfo);
        ((Activity) mContext).startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_outbound;
    }

    @Override
    public void initView() {
        pictureAdapter = new PictureAdapter(mContext,true);
        noScrollgridview.setAdapter(pictureAdapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (arg2 == attachPaths.size()) {
                    //
                    showPictureView();
                } else {
                    //预览
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                    intent.setCurrentItem(arg2); // 当前选中照片的下标
                    intent.setPhotoPaths(attachPaths); // 已选中的照片地址
                    startActivityForResult(intent, AppConstant.REQUEST_PREVIEW_CODE);
                }
            }
        });
        logisticsInfo = (LogisticsInfo) getIntent().getSerializableExtra("logisticsInfo");
        orderId = getIntent().getStringExtra("orderId");
        timeText.setText(TimeUtil.formatData(TimeUtil.dateFormatYMD, System.currentTimeMillis()));
        showTitle("出库准备", new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                isSubmitData = true;
                finish();
            }
        });
        productAdapter = new ProductAdapter(mContext, false);
        listview.setAdapter(productAdapter);
        if (logisticsInfo != null) {
            batchId = logisticsInfo.getBatch_id();
            attachPath = logisticsInfo.getAttach();
            if (!StringUtil.isEmpty(attachPath)){
                String[] arrays = attachPath.split("\\#\\*\\#");
                for (int i =0;i<arrays.length;i++){
                    attachPaths.add(arrays[i]);
                }
                pictureAdapter.setSelectPaths(attachPaths);
            }
            noteEdit.setText(logisticsInfo.getRemark());
//            addText.setText("已添加");
        }
    }


    private void uploadFile(final UploadCallBack callBack){
        try {
            final ArrayList<String> imagePaths = attachPaths;
            String imageUrl = imagePaths.get(0);
            if (imageUrl.startsWith("http")){
                imagePaths.remove(0);
                if (imagePaths.size() != 0){
                    attachPath +=(imageUrl+"#*#");
                    callBack.getCallBack(imagePaths.size());
                    uploadFile(callBack);
                }else {
                    attachPath +=(imageUrl);
                    if (callBack != null){
                        callBack.getCallBack(0);
                    }
                }
            }else {
                DataRequestUtil.getInstance(mContext).uploadImage(mContext,"5", imageUrl, new FileUploadCallBack() {
                    @Override
                    public void success(FileInfo fileInfo) {
                        imagePaths.remove(0);
                        if (imagePaths.size() != 0){
                          attachPath +=(fileInfo.getFilePath()+"#*#");
                            callBack.getCallBack(imagePaths.size());
                            uploadFile(callBack);
                        }else {
                          attachPath +=(fileInfo.getFilePath());
                            if (callBack != null){
                                callBack.getCallBack(0);
                            }
                        }
                    }

                    @Override
                    public void fail() {
                        LoadingDialog.cancelDialogForLoading();
                    }
                });

            }
        }catch (Exception e){

        }
    }
    /**
     * 显示照片弹出框
     */
    private void showPictureView(){
        DialogUtil.showPictureDialogView(mContext,true, new PictureCallBack() {
            @Override
            public void getCallBack(int type) {
                switch (type) {
                    case 1:
                        //相册选择
                        ImageConfig config = new ImageConfig();
                        config.minHeight = 400;
                        config.minWidth = 400;
                        config.mimeType = new String[]{"image/jpeg", "image/png"}; // 图片类型 image/gif ...
                        config.minSize = 1 * 1024 * 512; // 1Mb 图片大小
                        PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                        intent.setSelectModel(SelectModel.MULTI);
                        intent.setShowCarema(false); // 是否显示拍照， 默认false
                        intent.setMaxTotal(9); // 最多选择照片数量，默认为9
                        intent.setSelectedPaths(attachPaths); // 已选中的照片地址， 用于回显选中状态
                        // intent.setImageConfig(config);
                        startActivityForResult(intent, AppConstant.REQUEST_CAMERA_CODE);
                        break;
                    case 2:
                        //拍照
                        try {
                            if (captureManager == null) {
                                captureManager = new ImageCaptureManager(mContext);
                            }
                            Intent intent1 = captureManager.dispatchTakePictureIntent();
                            startActivityForResult(intent1, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        });
    }
    @OnClick({R.id.add_pic_img, R.id.ensure_btn, R.id.chuku_product_parent})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_pic_img:
//                startActivityForResult(TakePhotoUploadActivity.getTakePhotoStartIntent(mContext,
//                        DO_BIG_IMAGE, 1, 1, 640, 640,true,attachPath), UPLOAD_IMG);

                break;
            case R.id.chuku_product_parent:
//                ProductListActivity.startAction(mContext, orderId, batchId, productList, 1000);
                ProductListWebViewActivity.startAction(mContext, orderId, batchId,productItems,1001);
                break;
            case R.id.ensure_btn:
                if (attachPaths.size() == 0) {
                    showShortToast("产品授权书不能为空！");
                    return;
                }
//                if (productList == null || productList.size() == 0) {
//                    showShortToast("请输入出库货品信息！");
//                    return;
//                }
//                if (!productAdapter.isHaveData()) {
//                    showShortToast("产品数量不能为空！");
//                    return;
//                }
                final String remark = noteEdit.getText().toString().trim();
                if (StringUtil.isEmpty(remark)) {
                    showShortToast("请输入备注信息！");
                    return;
                }
//                Map<String, String> map = productAdapter.getAllPrice();
//                final String allPrice = map.get("price");
//                final String items = map.get("items");
                // TODO: 2017/12/21 临时用
                final String batchSN = orderId + "_101";
                attachPath = "";
                LoadingDialog.showDialogForLoading((Activity) mContext,"数据提交中",false);
                uploadFile(new UploadCallBack() {
                    @Override
                    public void getCallBack(int position) {
                        if (position == 0){
                         mPresenter.outboundSubmit(orderId, batchSN, batchId, 3, attachPath, productToTalPrice, remark, 1, productItems);
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case AppConstant.REQUEST_CAMERA_CODE:
                    ArrayList<String> arrays = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                    attachPaths = arrays;
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                // 拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        // 照片地址
                        String imagePaht = captureManager.getCurrentPhotoPath();
                        ClipImageActivity.startAction((Activity) mContext,Uri.parse(imagePaht));
                    }
                    break;
                //裁剪
                case 1234:
                    Uri uri  = data.getParcelableExtra("imageUri");
                    String path = FileUtil.getImageAbsolutePath(this,uri);
                    attachPaths.add(path);
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                // 预览
                case AppConstant.REQUEST_PREVIEW_CODE:
                    ArrayList<String> arrayss = data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT);
                    attachPaths = arrayss;
                    pictureAdapter.setSelectPaths(attachPaths);
                    break;
                case 1000:
                    productList = (List<ProductInfo>) data.getSerializableExtra("productList");
                    if (productList != null && productList.size() > 0) {
                        productListParent.setVisibility(View.VISIBLE);
                        productAdapter.addAllData(productList);
                        StringUtil.setListViewHeightBasedOnChildren(listview);
                    } else {
                        productListParent.setVisibility(View.GONE);
                    }
                    break;
                case 1001:
                    String result =  data.getStringExtra("productList");
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        productItems = jsonObject.optString("data");
                        if (StringUtil.isEmpty(productItems)){
                            addText.setText("添加");
                        }else {
                            JSONArray array = new JSONArray(productItems);
                            if (array != null && array.length() > 0){
                                addText.setText("已添加");
                            }else {
                                addText.setText("添加");
                            }
                        }
                        productToTalPrice = jsonObject.optString("totalPrice");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    productListParent.setVisibility(View.GONE);
                    break;
//                case UPLOAD_IMG:
//                    if (data != null && data.getExtras() != null) {
//                        final Uri avatarUri = data.getExtras().getParcelable("PATH");
//                        if (avatarUri != null) {
//                            String imgPath = avatarUri.getPath();
//                            try {
//                                DataRequestUtil.getInstance(mContext).uploadImage("5", Base64.encodeFromFile(imgPath), new FileUploadCallBack() {
//                                    @Override
//                                    public void success(FileInfo fileInfo) {
//                                        attachPath = fileInfo.getFilePath();
//                                        addPicImg.setImageURI(avatarUri);
//                                    }
//
//                                    @Override
//                                    public void fail() {
//                                    }
//                                });
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                    break;
            }
        }
    }

    @Override
    public void outboundSubmitSuccess() {
        LoadingDialog.cancelDialogForLoading();
        isSubmitData = true;
        finish();
    }

    @Override
    public void outboundSubmitFail() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("isSubmitData", isSubmitData);
        setResult(RESULT_OK, intent);
        super.finish();
    }
}
